package com.zhongshu.common.response;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: ThrowsHandler
 * @Description: 自定义异常返回类
 * @author: 星~
 * @date: 2021/9/8 0008 上午 9:13
 */

@RestControllerAdvice(basePackages = "com.zhongshu。controller")
@Slf4j
public class ThrowsHandler {

/*
    JSR303 暂时不用
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题:{}-----,异常类型:{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        // 获取校验的错误结果
        result.getFieldErrors().forEach(item -> {
            String defaultMessage = item.getDefaultMessage();
            String field = item.getField();
            errorMap.put(field, defaultMessage);
        });
        return R.error().put("data",errorMap);
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", errorMap);
    }*/

    @ExceptionHandler(value = Throwable.class)
    public R handleVaildException(Throwable e) {
        String message = e.getMessage();
        System.out.println("异常为:" + message);
        if (message.contains("--")) {
            String[] split = message.split("--");
            return R.error(Integer.parseInt(split[0]),
                    split[1]);
        }
        return R.error(BizCodeEnum.UNKNOW_EXEPTION.getCode(),
                BizCodeEnum.UNKNOW_EXEPTION.getMsg());
    }
}
